const router = require("express").Router();
const Movies = require("../../models/movies");

router.post("/", (req, res) => {
  res.send(req.body);
});
// router.get('/', async (req, res) => {
//     const movies = await Movies.find({}).sort({
//         _id: -1
//     });
//     res.render('movies/index', {
//         movies,
//         title: '经典影片'
//     });
// })
router.get("/", async (req, res) => {
  const page = req.query.page * 1 || 1;
  const per = req.query.per * 1 || 10;
  const query = {};
  if (req.query.title) {
    query.title = new RegExp(req.query.title);
  }
  const movies = await Movies.find(query)
    .sort({
      _id: -1,
    })
    .skip((page - 1) * per)
    .limit(per);
  const totals = await Movies.count(query);
  res.json({
    totals,
    pages: Math.ceil(totals / per),
    movies,
  });
});

module.exports = router;
